#! /usr/bin/python
## Firoj Alam
## The purpose of this script is to use LIWC (http://www.liwc.net/) API.
## LIWC calculates the degree to which people use different categories of words
## across a wide array of texts, including emails, speeches, poems, or transcribed daily speech.

import urllib2
import json
import time

## The JSON content type header
headers = {}
headers['Content-Type'] = 'application/json'
headers['Accept'] = 'application/vnd.lexical.v0'

def post_data():
    ## URL to post the data
    url = "http://liwc.lexical.io/api/jobs";

    ## Input parameters to post the data as json format. If you have access to the
    ## LIWC API then please look for the http://liwc.lexical.io/api/docs to understand
    ## what each parameter means.
    json_dict = {
            "description":"An example",
            "login": "Your LOGIN NAME",
            "token":"YOUR TOKEN NUMBER",
            "content":
                    {
                            "text1":"This is the test text for text1 to send to the API as an example",
                            "text2":"This is the test text for text2 to send to the API",
                            "text3":"This is the test text for text3 to send to the API",
                            "text4":"the content parameter is a hash (dictionary) of key:value pairs name:text"
                    },
       "options":
          {
            "pos":True
          }
    }

    ## Convert json_dict to JSON
    json_data = json.dumps(json_dict);
    ## Convert str to bytes (ensure encoding is OK)
    post_data = json_data.encode('utf-8');
    request = urllib2.Request(url, post_data,headers);
    response = urllib2.urlopen(request);
    #print response.info()
    ## Read response for 'job id', which is later used to access the processed output.
    data = response.read();
    #print data
    job_id=0;
    data = json.JSONDecoder('utf-8').decode(data);
    job_id=data["job_id"];
    #print job_no
    return job_id;

def get_data(job_id):
    login="Your LOGIN NAME"
    token="YOUR TOKEN NUMBER"
    urlget = "http://liwc.lexical.io/api/jobs/"+str(job_id)+"?login="+login+"&token="+token
    time.sleep(5) # Time for processing the posted data 
    request = urllib2.Request(urlget)
    response = urllib2.urlopen(request)
    data = response.read()
    #data = json.JSONDecoder('utf-8').decode(data) # decoding the json
    print data

if __name__ == "__main__":
    job_id=post_data();
    print "Job posted"
    get_data(job_id);
    print "Done"
